package com.fowo.api.service.handleWork;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.Payable;
import com.fowo.api.entity.StockIn;
import com.fowo.api.mapper.PayableMapper;
import com.fowo.api.mapper.StockInMapper;
import com.fowo.api.model.payable.PayableRevocationAction;
import com.fowo.api.model.payable.PayableVo;
import com.fowo.api.model.payable.product.PayableProductItemVo;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.service.PayableService;
import com.fowo.api.service.StockInService;
import com.fowo.api.service.impl.PayableServiceImpl;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Component
public class PayableRevocation implements PayableRevocationAction {
    @Resource
    private PayableService payableService;
    @Resource
    private StockInMapper stockInMapper;
    @Resource
    private StockInService stockInService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void run(Long id) throws Exception {
        PayableVo payable = payableService.getVoById(id);
        Assert.notNull(payable,"未查到应付单!");
        Assert.isTrue(payable.getStauts().equals("0"),"应付单已审核");

        StockIn stockIn = stockInMapper.selectOne(Wrappers.lambdaQuery(StockIn.class).eq(StockIn::getOrderSn,payable.getWarehouseSn()));
        StockInVo stockInVo = stockInService.getVoById(stockIn.getId());

        stockInVo.setGenerateAp("0");
        stockInVo.setRevocation("1");
        stockInVo.setRejectRemark(payable.getRejectRemark());
        final List<PayableProductItemVo> productItems = payable.getProductltem();
        for(StockInProductItemVo item : stockInVo.getProductList()){
            final PayableProductItemVo payableProductItemVo = productItems.stream().filter(p -> p.getProductId().equals(item.getProductId()) && p.getNum().intValue() == item.getQuantity().intValue()).findFirst().get();
            item.setRemarks(payableProductItemVo.getRemark());
        }
        stockInService.update(stockInVo);
        payableService.delete(id);
    }
}
